package flc.ast.fragment.timer;

import android.app.Dialog;
import android.graphics.Color;
import android.net.Uri;

import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SeekBar;

import com.bigkoo.pickerview.adapter.ArrayWheelAdapter;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.UriUtils;
import com.contrarywind.adapter.WheelAdapter;
import com.contrarywind.view.WheelView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;

import flc.ast.R;
import flc.ast.activity.RecentAddActivity;
import flc.ast.activity.TimerEditActivity;
import flc.ast.bean.MyTimerBean;
import flc.ast.databinding.FragmentTimeBinding;
import flc.ast.utils.AppSpUtils;
import flc.ast.utils.AudioPlayerImpl;
import in.xiandan.countdowntimer.CountDownTimerSupport;
import in.xiandan.countdowntimer.OnCountDownTimerListener;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.view.StkTextView;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link TimeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class TimeFragment extends BaseNoModelFragment<FragmentTimeBinding> {

    public static int selPosition;
    private Dialog mySelTimeDialog;
    private WheelView wheelView1, wheelView2, wheelView3;
    private long time;
    private List<MyTimerBean> listShow = new ArrayList<>();
    private AudioPlayerImpl mAudioPlayer;
    private CountDownTimerSupport mTimer;
    private boolean isStart;
    private SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");


    @Override
    protected int onCreate() {
        return R.layout.fragment_time;
    }

    @Override
    protected void initView() {
        mDataBinding.ivAdd.setOnClickListener(this);
        mDataBinding.rlTime.setOnClickListener(this);
        mDataBinding.ivEdit.setOnClickListener(this);
        mDataBinding.ivList.setOnClickListener(this);
        mDataBinding.tvStart.setOnClickListener(this);

        mAudioPlayer = new AudioPlayerImpl();

        format.setTimeZone(TimeZone.getTimeZone("UTC"));

        mDataBinding.sbVolume.setProgress(100);
        mDataBinding.sbVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                float volume = progress / 100f;
                mAudioPlayer.setVolume(volume);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        //选择时间弹框
        selTimeDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivAdd://添加
                TimerEditActivity.myBean = null;
                startActivity(TimerEditActivity.class);
                break;
            case R.id.rlTime://时间
                if (listShow.size() == 0) return;
                mySelTimeDialog.show();
                break;
            //选择时间弹框
            case R.id.ivDialogSelTimeCancel://取消
                mySelTimeDialog.dismiss();
                break;
            case R.id.tvDialogSelTimeRight://确定
                mySelTimeDialog.dismiss();
                updateTimer();
                break;
            case R.id.ivEdit://编辑
                if (listShow.size() == 0) {
                    TimerEditActivity.myBean = null;
                    startActivity(TimerEditActivity.class);
                } else {
                    TimerEditActivity.myBean = listShow.get(selPosition);
                    startActivity(TimerEditActivity.class);
                }
                break;
            case R.id.ivList://最近添加
                startActivity(RecentAddActivity.class);
                break;
            case R.id.tvStart://开始/暂停
                if (isStart) {
                    isStart = false;
                    mDataBinding.tvStart.setText(getString(R.string.start_clock));
                    if (mTimer != null) {
                        mTimer.stop();
                    }
                } else {
                    if (listShow.size() == 0) return;
                    isStart = true;
                    mDataBinding.tvStart.setText(getString(R.string.stop_clock));
                    mTimer = new CountDownTimerSupport(time, 1000);
                    mTimer.setOnCountDownTimerListener(new OnCountDownTimerListener() {
                        @Override
                        public void onTick(long millisUntilFinished) {
                            // 倒计时间隔
                            mDataBinding.tvTime.setText(TimeUtils.millis2String(millisUntilFinished, format));
                        }

                        @Override
                        public void onFinish() {
                            // 倒计时结束
                            Uri uri = Uri.parse("android.resource://" + AppUtils.getAppPackageName() + "/" + listShow.get(selPosition).getRing());
                            mAudioPlayer.play(UriUtils.uri2File(uri).getPath());
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    mAudioPlayer.stop();
                                }
                            }, 5000);
                            isStart = false;
                            mDataBinding.tvStart.setText(getString(R.string.start_clock));
                        }

                        @Override
                        public void onCancel() {
                            // 倒计时手动停止
                        }
                    });
                    mTimer.start();
                }
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        getData();
    }

    private void getData() {
        listShow.clear();
        List<MyTimerBean> listSp = AppSpUtils.getTimerList();
        if (listSp != null && listSp.size() > 0) {
            listShow.addAll(listSp);
            setTime(listSp.get(selPosition).getHour(), listSp.get(selPosition).getMinute(), listSp.get(selPosition).getSecond());
            mDataBinding.tvTag.setText(listSp.get(selPosition).getTag());
            mDataBinding.tvRing.setText(listSp.get(selPosition).getRingName());
        } else {
            mDataBinding.tvTime.setText(getString(R.string.time_zero));
            mDataBinding.tvTag.setText("");
            mDataBinding.tvRing.setText("");
        }
    }


    //修改计时器
    private void updateTimer() {
        //选择的日期
        int hour = wheelView1.getCurrentItem();
        int minute = wheelView2.getCurrentItem();
        int second = wheelView3.getCurrentItem();
        //保存数据
        List<MyTimerBean> listSp = AppSpUtils.getTimerList();
        if (listSp != null && listSp.size() != 0) {
            listSp.get(selPosition).setHour(hour);
            listSp.get(selPosition).setMinute(minute);
            listSp.get(selPosition).setSecond(second);
            AppSpUtils.savTimerList(listSp);
        }
        setTime(hour, minute, second);
    }

    //设置时间
    private void setTime(int hour, int minute, int second) {
        time = hour * 60 * 60 * 1000L + minute * 60 * 1000L + second * 1000L;
        mDataBinding.tvTime.setText(TimeUtils.millis2String(time, format));
    }

    //选择时间弹框
    private void selTimeDialog() {
        mySelTimeDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_sel_time, null);
        mySelTimeDialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = mySelTimeDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.TOP);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        DisplayMetrics dm = getResources().getDisplayMetrics();
        lp.width = (int) (dm.widthPixels * 1);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView dialogCancel = inflate.findViewById(R.id.ivDialogSelTimeCancel);
        StkTextView dialogRight = inflate.findViewById(R.id.tvDialogSelTimeRight);
        wheelView1 = inflate.findViewById(R.id.wheel_view1);
        wheelView2 = inflate.findViewById(R.id.wheel_view2);
        wheelView3 = inflate.findViewById(R.id.wheel_view3);
        dialogCancel.setOnClickListener(this);
        dialogRight.setOnClickListener(this);
        wheelView1.setDividerColor(Color.parseColor("#FFFFFF"));
        wheelView1.setTextColorCenter(Color.parseColor("#005C9B"));
        wheelView1.setLineSpacingMultiplier(2.5f);
        wheelView1.setDividerType(WheelView.DividerType.WRAP);
        wheelView1.setCurrentItem(0);
        wheelView1.setItemsVisibleCount(3);
        wheelView1.setCyclic(true);
        wheelView1.setTextSize(32);
        wheelView2.setDividerColor(Color.parseColor("#FFFFFF"));
        wheelView2.setTextColorCenter(Color.parseColor("#005C9B"));
        wheelView2.setLineSpacingMultiplier(2.5f);
        wheelView2.setDividerType(WheelView.DividerType.WRAP);
        wheelView2.setCurrentItem(0);
        wheelView2.setItemsVisibleCount(3);
        wheelView2.setCyclic(true);
        wheelView2.setTextSize(32);
        wheelView3.setDividerColor(Color.parseColor("#FFFFFF"));
        wheelView3.setTextColorCenter(Color.parseColor("#005C9B"));
        wheelView3.setLineSpacingMultiplier(2.5f);
        wheelView3.setDividerType(WheelView.DividerType.WRAP);
        wheelView3.setCurrentItem(0);
        wheelView3.setItemsVisibleCount(3);
        wheelView3.setCyclic(true);
        wheelView3.setTextSize(32);
        //设置滚轮数据
        List<String> listHour = new ArrayList<>();//时
        for (int i = 0; i < 24; i++) {
            listHour.add(String.valueOf(i));
        }
        List<String> listMinute = new ArrayList<>();//分
        for (int i = 0; i < 60; i++) {
            listMinute.add(String.valueOf(i));
        }
        List<String> listSecond = new ArrayList<>();//秒
        for (int i = 0; i < 60; i++) {
            listSecond.add(String.valueOf(i));
        }
        WheelAdapter adapter1 = new ArrayWheelAdapter(listHour);
        wheelView1.setAdapter(adapter1);
        WheelAdapter adapter2 = new ArrayWheelAdapter(listMinute);
        wheelView2.setAdapter(adapter2);
        WheelAdapter adapter3 = new ArrayWheelAdapter(listMinute);
        wheelView3.setAdapter(adapter3);
    }

}